from  pydantic import BaseModel,HttpUrl,ValidationError

#类似Java的pojo但更强大
# class UserProfile(BaseModel):
#     username: str
#     age: int = 18
#     email: str | None = None

#实例化验证
# user1 = UserProfile(username="user1")
# print(user1)
#
# user2 = UserProfile(username="user2",age="20")
# print(user2.age)

#案例2
# try:
#     UserProfile(username=123)
# except ValueError as e:
#     print(e.errors())

#案例3
# class WebSite(BaseModel):
#     url: HttpUrl
#     visits:int = 0
#     tags: list[str] = []
#
# valid_data = {
#     "url":"https://www.baidu.com",
#     "visits":100,
#     "tags":["python","fastapi"],
# }

# try:
#     website = WebSite(**valid_data)
#     print(website)
# except ValidationError as e:
#     print(e.errors())

# try:
#     website = WebSite(url="https://www.baidu.com",visits=100)
#     print(website)
# except ValidationError as e:
#     print(e.errors())

#案例4
class Item(BaseModel):
    name: str
    price: float

#从Json自动解析（类似Jackson）
data = '{"name":"Widget","price":"3.14"}'
item = Item.model_validate_json(data)

#导出为字典 (类似Java 的POJO转Map)
print(item.model_dump())

#输出完整Json Schema
print(Item.model_json_schema())